package com.ljkj.blockpay.ui.activity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.Adapter;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.kongzue.baseokhttp.util.JsonMap;
import com.ljkj.blockpay.R;
import com.ljkj.blockpay.basedata.BaseActivity;
import com.ljkj.blockpay.databinding.ActivityRechargeBinding;
import com.ljkj.blockpay.model.RechargeModel;
import com.ljkj.blockpay.presenter.RechargePresenter;
import com.ljkj.blockpay.presenter.inter.RechargeInter;
import com.ljkj.blockpay.ui.adapter.CommonSelectAdapter;
import com.ljkj.blockpay.ui.adapter.RechargeAdapter;
import com.ljkj.blockpay.util.ToggleToActivity;
import com.ljkj.blockpay.widget.ClickListener;
import com.ljkj.blockpay.widget.CommonDialog;
import com.ljkj.blockpay.widget.GridSpaceItemDecoration;
import com.ljkj.blockpay.widget.ScreenshotUtil;
import com.luck.picture.lib.tools.ToastUtils;
import com.tbruyelle.rxpermissions3.Permission;
import com.tbruyelle.rxpermissions3.RxPermissions;
import com.yxing.ScanCodeConfig;
import com.yxing.utils.SizeUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

//充值界面
public class RechargeActivity extends BaseActivity<ActivityRechargeBinding, RechargePresenter> implements ClickListener , RechargeInter.RechargeInterView {

    private CommonDialog mSelectdialog;
    private Bitmap QRbitmap;
    private RechargeAdapter mRechargeAdapter;
    private RecyclerView currencylist;
    private String address;
    private CommonSelectAdapter mConnomAdapter;
    private CommonDialog mCurrencyDialog;
    private String currencyName;
    private String currencyImg;
    private List<RechargeModel.NetworkDTO> networkList;
    private String currencyMin;
    private String networkName;
    public static final String[] permissionsGroup =new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    @Override
    public int initContentView() {
        return R.layout.activity_recharge;
    }

    @Override
    protected RechargePresenter createPresenter() {
        return new RechargePresenter(this, this);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        getPresenter().getNetAccuracy(1);
        mSelectdialog = CommonDialog.Builder.with(this).setContentView(R.layout.select_coinnet)
                .setOnClickListener(R.id.tv_close, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mSelectdialog.dismiss();
                    }
                }).setCancelable(true).fullWidth().formBottom(true).create();
        GridLayoutManager lManager = new GridLayoutManager(this, 2);
        currencylist = mSelectdialog.findViewById(R.id.rv_currency);
        currencylist.setLayoutManager(lManager);
        mRechargeAdapter = new RechargeAdapter(R.layout.currnet_layout);
        currencylist.setAdapter(mRechargeAdapter);


        mRechargeAdapter.setOnItemClickListener((adapter, view, position) -> {
            List<RechargeModel.NetworkDTO> modelList = mRechargeAdapter.getData();
            binding.textSwitch.setText(modelList.get(position).getNetworkType());
            getPresenter().getRecharge(currencyName, modelList.get(position).getNetworkType());
            mSelectdialog.dismiss();
        });
    }

    @Override
    protected void initData() {
        super.initData();
        binding.setOnClick(this::onClick);
        binding.topTitle.setLeftBackFinish(this);
        binding.topTitle.mContentTitle.setText("充值");

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.rl_none:
                ToggleToActivity.toSelectCurrencyActivity(this, 10);
                break;
            case R.id.rl_netselect:
                mSelectdialog.show();
                break;
            case R.id.btn_savecode:
                savecode();
                break;
            case R.id.tv_notice:

                break;
            case R.id.iv_copyaddress:
                ClipboardManager manager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("Label", binding.tvCoinaddress.getText().toString());
                manager.setPrimaryClip(clipData);
                ToastUtils.s(RechargeActivity.this, "复制成功");
                break;
        }
    }

    private void savecode() {
        if (address != null){
            new RxPermissions(RechargeActivity.this).requestEachCombined(permissionsGroup).subscribe(new Observer<Permission>() {
                @Override
                public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
                }

                @Override
                public void onNext(@io.reactivex.rxjava3.annotations.NonNull Permission permission) {
                    new AsyncTask<Void, Void, Bitmap>() {
                        @SuppressLint("StaticFieldLeak")
                        @Override
                        protected Bitmap doInBackground(Void... params) {
                            Bitmap bitmap = null;
                            try {
                                bitmap = Glide.with(RechargeActivity.this)
                                        .asBitmap()
                                        .load(currencyImg)
                                        .submit(150, 150).get();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            return bitmap;
                        }

                        @Override
                        protected void onPostExecute(Bitmap bitmap) {
                            View views = LayoutInflater.from(RechargeActivity.this).inflate(R.layout.activity_save_picture, null, false);
                            //这里传值屏幕宽高，得到的视图即全屏大小
                            ImageView QR = views.findViewById(R.id.iv_savepicture);
                            TextView qrname = views.findViewById(R.id.tv_currencyname);
                            TextView currencyaddress = views.findViewById(R.id.tv_moneyaddress);
                            TextView rednotice = views.findViewById(R.id.tv_rednotice);
                            TextView minmoney = views.findViewById(R.id.tv_minmoney);

                            QRbitmap = ScanCodeConfig.createQRcodeWithLogo(address, bitmap);
                            QR.setImageBitmap(QRbitmap);
                            qrname.setText(currencyName);
                            currencyaddress.setText(address);
                            rednotice.setText(getResources().getString(R.string.notice_tv)+currencyName+getResources().getString(R.string.notice_tv1));
                            minmoney.setText(getResources().getString(R.string.recharge)+currencyMin+networkName+getResources().getString(R.string.recharge2));

                            Bitmap bitmap3 = createBitmap3(views, getWindow().getDecorView().getWidth(), getWindow().getDecorView().getHeight());
                            ScreenshotUtil.saveImageToGallery(bitmap3, RechargeActivity.this);
                            ToastUtils.s(RechargeActivity.this,"保存成功");

                        }
                    }.execute();

                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

        } else {
            ToastUtils.s(this,"图片为空");
        }

    }

    public Bitmap createBitmap3(View v, int width, int height) {
        //测量使得view指定大小
        int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
        int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
        v.measure(measuredWidth, measuredHeight);
        //调用layout方法布局后，可以得到view的尺寸大小
        v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        Bitmap bmp = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        v.draw(c);
        return bmp;
    }

    @Override
    public void showNetAccuracy(List<RechargeModel> modelList) {
        if (modelList.size() != 0) {
            mRechargeAdapter.setNewInstance(modelList.get(0).getNetwork());
            currencyName = modelList.get(0).getCurrencyName();
            currencyImg = modelList.get(0).getCurrencyImg();
            networkList = modelList.get(0).getNetwork();

            binding.tvCurrency.setText(currencyName);
            Glide.with(baseContext).load(currencyImg).into(binding.ivIcon);
            for (int i = 0; i < networkList.size(); i++) {
                currencyMin = networkList.get(0).getCurrencyMin();
                networkName = networkList.get(0).getNetworkName();
                binding.tvContent.setText(getResources().getString(R.string.recharge)+currencyMin+networkName+getResources().getString(R.string.recharge2));
            }
        }
    }

    @Override
    public void showrecharge(JsonMap jsonMap) {
        address = jsonMap.getString("address");
        QRbitmap = ScanCodeConfig.createQRCode(address);
        binding.ivQrcode.setImageBitmap(QRbitmap);
        binding.tvCoinaddress.setText(address);
    }


    @Override
    public void createOrderSuccess() {

    }

    @Override
    public void SearchCurrencySuccess(JsonMap jsondata) {

    }

    @Override
    public void getOrderDetails(JsonMap jsonMap) {
        getPresenter().preOrderId = jsonMap.getString("preOrderId");
        String orderId = jsonMap.getString("orderId");
    }

    @Override
    public void getOrderDetails2(JsonMap jsonMap) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 100) {
            return;
        }
        if (data.getExtras() != null) {
            Bundle bundle = data.getExtras();
            JsonMap jsonMap = JsonMap.parse(bundle.getString("jsonMap"));
            switch (requestCode) {
                case 10:
                    currencyName = jsonMap.getString("currencyName");
                    currencyImg = jsonMap.getString("currencyImg");
                    binding.tvCurrency.setText(currencyName);
                    Glide.with(baseContext).load(currencyImg).into(binding.ivIcon);
                    for (int i = 0; i < networkList.size(); i++) {
                        binding.tvContent.setText(getResources().getString(R.string.recharge)+networkList.get(i).getCurrencyMin()+currencyName+getResources().getString(R.string.recharge2));
                    }
                    break;
                default:
                    break;
            }

        }
    }
}